<?php

namespace App\Admin\Controllers;

use App\Models\User;
use App\Models\Patient;
use App\Models\DoctorUser;
use App\Models\Order;
use App\Models\Goods;
use App\Models\OrderDetail;
use App\Models\DoctorRole;

use App\Http\Controllers\Controller;
use Illuminate\Routing\Router;
use App\Models\WxUser;
use App\Models\TagImage;
use App\Models\TagTask;
use Request;
use Illuminate\Support\Facades\Log;

include_once "common.php";

class DocController extends Controller
{
    function test(){
        echo 'ss';
    }

    // 封装response
    function res($code,$msg,$data=NULL){
      if($data){
        return response()->json(array('code'=>$code, 'msg'=>$msg, 'data'=>$data));
      }
      return response()->json(array('code'=>$code, 'msg'=>$msg));
    }
    // 搜索和分页
    function search_and_paging($db,$input_list,$start,$limit){
      // 根据条件搜索
        foreach($input_list as $k=>$v){
          if($v){
            $db->where($k,$v);
          }
        }       
        // 分页
        if ($start !== NULL && $limit !== NULL){
            if ($start <= 0) $start = 0;
            if ($limit > 20) $limit = 20;
            $db=$db->offset($start)->take($limit);
        }
        return $db;
    }
    function get_user_data_by_cookie(){
        $token= request()->cookie('token');
        if(!$token) return 0;

        $id=substr($token,16);
        
        $db=DoctorUser::find($id);
        
        if(!$db) return 0;
        if ($db->token != $token) return 0;
        
        $res=$this->get_user_data_by_id($id);
        return $res;
    }
    
    // 获取单个用户信息
    function get_user_data_by_id($id){
      //用户信息数组
      $db=DoctorUser::find($id)->toArray();
      unset($db['password']);

      $role_data=$this->get_role_data($db['role']);
      
      $db['profit_rate'] = $role_data['profit_rate'];
      $db['des'] = $role_data['des'];
      $db['role_key'] = $role_data['role_key'];
      return $db;
    }
    // 获取角色信息
    function get_role_data($role_id){
      $db = DoctorRole::where('role_id',$role_id)->first()->toArray();
      return $db;
    }
    // 获得下属用户的数组
    function get_my_user_list($id,$role_key,$user_role){
      $res = array();
      $db = DoctorUser::where($role_key,$id)->where('role',$user_role)->get()->toArray();
      foreach($db as $v){
        $res[] = $v['id'];
      }
      return $res;
    }
    // 医生端H5 api 登录 post {mobile,password}
    function login(){
        $mobile = Request::input('mobile');
        $password = Request::input('password');
        $result = DoctorUser::where('mobile',$mobile)->get()->first();
        if(!$result){
            return $this->res(1,'用户名不存在');
        }
        $repassword = $result['password'];
        if($repassword != $password){
            return $this->res(1,'密码错误');
        }
        //return var_dump($result);
        $token=random_string(16).$result['id'];
        $db=DoctorUser::find($result['id']);
        $db->token=$token;
        $db->save();
        return response()->json(array('code'=>0, 'msg'=>'ok','data'=>[
                'id'=>$result['id'],
                'role'=>$result['role'],
                'profit'=>$result['profit'],
                'mobile'=>$result['mobile'],
                'name'=>$result['name'],
                'father_id'=>$result['father_id']
                ]))->withCookie("token",$token, 120);
    }
    
    /**--------------数据看板----------------------------**/
    //获得数据看板 route_path /get_order_data
    function get_data_kanban(){
      $id = Request::input('id');
      $res = $this->get_user_data_by_cookie();
      if(!$res){
        return $this->res(1,'验证失败');
      }
      
      //普通用户的角色id 目前为1     
      $user_role = 1;
      $role_key = $res['role_key'];
      $profit_rate = $res['profit_rate'];
      
      $date = array(
        'today'=>['start'=>date("Y-m-d 00:00:00"),'end'=>NULL],
        'yesterday'=>['start'=>date("Y-m-d 00:00:00",strtotime("-1 day")),'end'=>date('Y-m-d 00:00:00')],
        'month'=>['start'=>date("Y-m-01 00:00:00"),'end'=>NULL],
        'year'=>['start'=>date("Y-01-01 00:00:00"),'end'=>NULL],
        'all'=>['start'=>NULL,'end'=>NULL]
      );
      // 获取不同时间段用户数量
      $user_res = $this->get_user_count_by_date($id,$role_key,$user_role,$date);      
      // 获取不同时间段销售额和利润
      $order_res = $this->get_order_and_price_count_by_date($id,$role_key,$user_role,$date);      
      // 获取提成
      $profit_res = $this->get_profit_by_order_res($order_res,$profit_rate);     
      $result = array();
      foreach($date as $k=>$v){
        $result[$k]['user_count'] = $user_res[$k]['user_count'];
        $result[$k]['all_price'] = $order_res[$k]['all_price'];
        $result[$k]['order_count'] = $order_res[$k]['order_count'];
        $result[$k]['profit'] = $profit_res[$k]['profit'];
      }
      return $this->res(0,'success',$result);
    }
    
    /***
    ** id(int):管理人员的id
    ** user_role(int):普通用户的角色对应id 
    ** role_key(str):何种上级(ceo_id ? doctor_id ? store_id)
    ** date(arr):不同时间段的数组
    ** return(arr) 对应date数组的用户数量
    ***/
    function get_user_count_by_date($id,$role_key,$user_role,$date){
      $res = array();
      foreach($date as $k=>$v){
        $result = $this->get_user_data($id,$role_key,$user_role,$v['start'],$v['end']);
        $res[$k]['user_count'] = $result;
      }
      return $res;
    }
    /***
    **管理人员获得下属用户
    ** id(int):管理人员的id
    ** user_role(int):普通用户的角色对应id 
    ** role_key(str):何种上级(ceo_id ? doctor_id ? store_id)
    ** start(date):用户创建时间的开始(包含)
    ** end(date):用户创建时间的结束(不包含)
    ** return 用户数量
    ***/
    function get_user_data($id,$role_key,$user_role,$start,$end){    
      if($start == NULL && $end == NULL){
         return DoctorUser::where('role',$user_role)->where($role_key,$id)->count();
      }
      if($start == NULL){
        return DoctorUser::where('role',$user_role)->where($role_key,$id)->where('created_at','<',$end)->count();
      }
      if($end == NULL){
        return DoctorUser::where('role',$user_role)->where($role_key,$id)->where('created_at','>=',$start)->count();
      }
      $db = DoctorUser::where('role',$user_role)->where($role_key,$id)
            ->where('created_at','>=',$start)->where('created_at','<',$end);                
      return $db->count();
    }
    
    //管理人员获得下属用户的订单
    function get_order_and_price_count_by_date($id,$role_key,$user_role,$date){
      $res = array();
      $user_list = $this->get_my_user_list($id,$role_key,$user_role);
      
      foreach($date as $k=>$v){
        $result = $this->get_order_and_price_count_by_user_list($user_list,$v['start'],$v['end']);
        $res[$k]['all_price'] = $result['all_price'];
        $res[$k]['order_count'] = $result['order_count'];
      }
     
      return $res;
    }
    
    // 根据用户列表获取订单数据
    function get_order_and_price_count_by_user_list($user_list,$start,$end){
      $res = array();
      
      if($start == NULL && $end == NULL){
        $db = Order::whereIn('user_id',$user_list)->where('pay_status','1');        
      } else if($start == NULL){
        $db = Order::whereIn('user_id',$user_list)->where('pay_status','1')->where('pay_time','<',strtotime($end));
      } else if($end == NULL){
        $db = Order::whereIn('user_id',$user_list)->where('pay_status','1')->where('pay_time','>=',strtotime($start));
      } else {
        $db = Order::whereIn('user_id',$user_list)
            ->where('pay_status','1')
            ->where('pay_time','>=',strtotime($start))
            ->where('pay_time','<',strtotime($end));
      }      
      if(!$db){
        return ['all_price'=>0,'order_count'=>0];
      }
      return ['all_price'=>($db->sum('price')),'order_count'=>($db->count())];
    }
    
    function get_profit_by_order_res($order_res,$profit_rate){
      $res = array();
      foreach($order_res as $k=>$v){
        $res[$k]['profit'] = round($v['all_price'] * $profit_rate,2);
      }
      return $res;
    }
    /**--------------------数据看板end----------------------------**/
    
    /**------------------------医生管理-----------------------------**/
    function search_doctor(){
      $name = Request::input('name');
      $mobile = Request::input('mobile');
      $myinfo = $this->get_user_data_by_cookie();
      if(!$myinfo){
        return $this->res(1,'验证失败');
      }
      $id = $myinfo['id'];
      $role_key = $myinfo['role_key'];
      // 目前医生的role为2
      $doctor_role = 2;
      $search_list = ['name'=>$name,'mobile'=>$mobile];
      $res = $this->get_doctor_list_by_id($id,$role_key,$doctor_role,$search_list);
      
      return $this->res(0,'ok',$res);
    }
    // 获取医生列表 id为管理者id
    function get_doctor_list_by_id($id,$role_key,$doctor_role,$search_list){        
      $db = DoctorUser::where('role',$doctor_role)->where($role_key,$id);
      // 搜索
      foreach($search_list as $k=>$v){
        if($v){
          $db->where($k,$v);
        }
      }
      return $db->get()->toArray();
    }
    /**------------------------医生管理end-----------------------------**/
}
